package cn.iocoder.yudao.framework.excel.core.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;

public class TimeConvert implements Converter<LocalTime> {

    // 支持的时间格式（按优先级尝试解析）
    private static final DateTimeFormatter[] SUPPORTED_FORMATTERS = {
            DateTimeFormatter.ofPattern("HH:mm:ss"),  // 默认格式
            DateTimeFormatter.ofPattern("HH:mm"),    // 支持无秒
            DateTimeFormatter.ofPattern("H:mm:ss")   // 支持单小时位（如 1:30:00）
    };

    @Override
    public Class<LocalTime> supportJavaTypeKey() {
        return LocalTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String timeStr = "";
        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            // Excel 数字（时间格式） → 转成 "HH:mm:ss"
            BigDecimal numberValue = cellData.getNumberValue();
            Date javaDate = DateUtil.getJavaDate(numberValue.doubleValue());
            timeStr = new SimpleDateFormat("HH:mm:ss").format(javaDate);
        } else if (cellData.getType() == CellDataTypeEnum.STRING) {
            timeStr = cellData.getStringValue();
        }

        if (StringUtils.isBlank(timeStr)) {
            throw new IllegalArgumentException("时间内容为空，无法解析");
        }

        // 尝试用多种格式解析时间
        for (DateTimeFormatter formatter : SUPPORTED_FORMATTERS) {
            try {
                return LocalTime.parse(timeStr, formatter);
            } catch (DateTimeParseException ignored) {
                // 尝试下一种格式
            }
        }
        throw new IllegalArgumentException("时间格式不支持，请使用 HH:mm:ss、HH:mm 或 H:mm:ss 格式");
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalTime localTime, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        // 统一格式化为 "HH:mm:ss" 写入 Excel
        return new WriteCellData<>(localTime.format(SUPPORTED_FORMATTERS[0]));
    }
}
